package com.domain;

import java.util.HashSet;
import java.util.Set;

/**
 * @描述
 * @时间 2017-10-23 20:03
 * @作者 肖亦鸣
 */
public class CircularQueueV3 {

    private Object[] datas;
    private int length = 10;
    private int index = 0;

    public CircularQueueV3() {
        init(length);
    }

    public CircularQueueV3(int length) {
        init(length);
    }

    /**
     * 初始化
     *
     * @param length
     */
    private void init(int length) {
        this.length = length;
        this.datas = new Object[length];
        for (int i = 0; i < length; i++) {
            datas[i] = new HashSet<Task>();
        }
    }

    public void add(Task task) {
        if (task == null || task.getIndex() < 0) {
            return;
        }
        int index = task.getIndex();
        if (task.getIndex() > length - 1) {
            index = task.getIndex() % length;
        }
        Set<Task> set = (HashSet<Task>) datas[index];
        set.add(task);
    }

    public Set<Task> get() {
        System.out.println(index);
        if (index < 0) {
            throw new IllegalArgumentException("参数错误");
        }
        if (index > length - 1) {
            throw new IllegalArgumentException("参数错误");
        }
        HashSet<Task> tasks = (HashSet<Task>) datas[index];
        index++;
        if (index == length) {
            index = 0;
        }
        return tasks;
    }

    public boolean isRun(Task task) {
        System.out.println("task.getIndex():" + (task.getIndex() + 1) + "index:" + (index));
        boolean isRun = task.getIndex() + 1 == index;
        if (isRun) {
            return true;
        } else {
            task.setIndex(task.getIndex() - length);
        }
        return false;
    }

}
